package com.yiqi.zhiyuan.feature.certification.model;

import android.text.TextUtils;

import com.suozhang.framework.component.http.RxDataProcessFactory;
import com.yiqi.zhiyuan.entity.bo.UploadCertificatesInfo;
import com.yiqi.zhiyuan.feature.certification.contract.VehicleContract;
import com.yiqi.zhiyuan.feature.certification.dependencies.vehicle.DaggerVehicleModelComponent;
import com.yiqi.zhiyuan.framework.api.ApiLib;
import com.yiqi.zhiyuan.framework.api.UserApi;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @ProjectName: ZhiYuan
 * @Description: 注册model
 * @Author: lijuwen
 * @CreateDate: 2019/3/13 13:07
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/3/13 13:07
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class VehicleModel implements VehicleContract.Model {
    @Inject
    UserApi api;

    public VehicleModel() {
        DaggerVehicleModelComponent.builder().apiComponent(ApiLib.apiComponent()).build().inject(this);
    }


    @Override
    public Observable<String> doInsertVehicle(List<UploadCertificatesInfo> certificatesInfo, String carNo, String carName, String carModelNo, String carColor, String id) {

        List<MultipartBody.Part> bodyHashMap = new ArrayList<>();

        for (int i = 0; i < certificatesInfo.size(); i++) {
            if (!certificatesInfo.get(i).getImgUrl().contains("http")) {
                File file = new File(certificatesInfo.get(i).getImgUrl());
                RequestBody requestFile = RequestBody.create(MediaType.parse("application/otcet-stream"), file);
                MultipartBody.Part filePart = MultipartBody.Part.createFormData(certificatesInfo.get(i).getName(), file.getName(), requestFile);
                bodyHashMap.add(filePart);
            }
        }
        RequestBody carNoBody = RequestBody.create(MediaType.parse("multipart/form-data"), carNo);
        RequestBody carNameBody = RequestBody.create(MediaType.parse("multipart/form-data"), carName);
        RequestBody carModelBody = RequestBody.create(MediaType.parse("multipart/form-data"), carModelNo);
        RequestBody carColorBody = RequestBody.create(MediaType.parse("multipart/form-data"), carColor);

        RequestBody idBody  = null;
        if (!TextUtils.isEmpty(id)) {
            idBody = RequestBody.create(MediaType.parse("multipart/form-data"), id);
        }
        return api.insertCarInDriver(bodyHashMap, carNoBody, carNameBody, carModelBody, carColorBody, idBody).compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer());
    }
}

